<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@ taglib prefix='sec' uri='http://www.springframework.org/security/tags'%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<script type="text/javascript" src="scripts/boot.js"></script>
	
	<style type="text/css">
	    .errorText
	    {
	        color:red;
	    }
    </style>
</head>
<body>
	<fieldset style="border:solid 1px #aaa;padding:3px;">
		<legend >订单基本信息(<a class="mini-button" onclick="historyOrders">相同客户编号已有<span id="orders_count"></span>个订单; 系统允许客户网退、退单数量是<span id="back_count"></span>个</a>)</legend>
		<form id="form1" method="post">
			<input class="mini-hidden" name="customerId" id="customer_id"/>
	        <table cellspacing="10" cellpadding="0">
	        	<tr>
	        		<td style="width:100px;" align="right">
	        			收货人：
	        		</td>
	        		<td colspan="4">
	        			<input requiredErrorText="收货人不能为空" name="name" style="width: 130px;" class="mini-textbox" required="true" vtype="maxLength:7"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			联系电话1：
	        		</td>
	        		<td colspan="2">
	        			<input requiredErrorText="联系电话不能为空" name="contactNo" style="width: 130px;" class="mini-textbox" required="true" vtype="int; maxLength:12; numType"/>
	        			<sec:authorize url='/orders_edit_outgoing.do'>
	        			<a class="mini-button" iconCls="icon-outgoing" onclick="outgoing1">外呼</a>
	        			</sec:authorize>
	        		</td>
	        		<td colspan="2" style="width:310px;" align="right">
	        			<span>联系电话2：</span>
	        			<input requiredErrorText="联系电话不能为空" emptyText="请输入联系电话2" name="contactNos" style="width: 130px;" class="mini-textbox" vtype="int; maxLength:12; numType"/>
	        			<sec:authorize url='/orders_edit_outgoing.do'>
	        			<a class="mini-button" iconCls="icon-outgoing" onclick="outgoing2">外呼</a>
	        			</sec:authorize>
	        		</td>
	        	</tr>
	        	<div id="win—outgoing" class="mini-window" showModal="false" allowDrag="false" showHeader="false" title="呼出" style="width: 200px;height: 110px;">
				    <input labelField="true" label="号码：" labelStyle="width: 40px;" class="mini-textbox" style="width:170px;margin-top: 7px;margin-left: 5px;" id="outNumId" enabled="false"/> 
				    <input labelField="true" label="加拨：" labelStyle="width: 40px;" class="mini-combobox" style="width:170px;margin-top: 7px;margin-left: 5px;" id="addNum"
				    	url="dictionary_cm_key_val_view.do?typeName=CALL_ADD_TYPE" textField="keyValue" valueField="keyValue" showNullItem="true" nullItemText="无"/> 
					<div style="text-align:center;padding-bottom: 5px;margin-top: 10px;">
						<a class="mini-button" onclick="outgoingOk" style="">呼出</a>
						<a class="mini-button" onclick="onClose2" style="margin-left: 30px;">关闭</a>
					</div>
				</div>
	        	<tr>
	        		<td align="right">
	        			地址：
	        		</td>
	        		<td colspan="4">
	        			<input  name="provinceId" id="province_val" class="mini-hidden"/>
			      		<input style="width: 130px;" id="province" name="pName" class="mini-textbox" required="true" onfocus="focusP" emptyText="请选择省份"/>
			      		<input name="cityId" class="mini-hidden" id="city_val" />
			      		<input class="mini-textbox" id="city" name="cName" style="width: 130px;" required="true" readOnly="true" emptyText="请选择城市"/>
			      		<input name="districtId" id="district_val" class="mini-hidden"/>
			      		<input class="mini-textbox" id="district" name="dName" style="width: 130px;" required="true" readOnly="true" emptyText="请选择区县"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			详细地址：
	        		</td>
	        		<td colspan="2">
	        			<input name="address" class="mini-textbox" style="width:265px;" required="true" />
	        		</td>
	        		<td style="width:90px;" align="right">
	      				邮编：
	        		</td>
	        		<td>
	      				<input class="mini-textbox" emptyText="请输入邮编" name="zipCode" style="width: 130px;"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			备注：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" emptyText="请输入备注" name="ordersRemark" style="width: 524px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			是否开发票：
	        		</td>
	        		<td colspan="2">
	        			<input name="invoice" emptyText="请选择..." showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" valueField="keyName" textField="keyValue"
	               			url="dictionary_om_key_val_view.do?typeName=ORDER_INVOICE_TYPE"/>
	        		</td>
	        		<td align="right">
	        			媒体：
	        		</td>
	        		<td>
	        			<input name="mediaId" showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" valueField="id" textField="name"
	               			url="orders_find_media.do" required="true"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			订单性质：
	        		</td>
	        		<td colspan="2">
	        			<input name="nature" emptyText="请选择..." showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" valueField="keyName" textField="keyValue"
	               			url="dictionary_om_key_val_view.do?typeName=ORDER_NATURE_TYPE"
	               			<sec:authorize url="/dictionary_om_key_val_view_read1.do">enabled="true"</sec:authorize> enabled="false"/>
	        		</td>
	        		<td align="right">
	        			物流公司：
	        		</td>
	        		<td>
	        			<input name="expressId" showNullItem="true" nullItemText="全部" emptyText="请选择..." style="width: 130px;" class="mini-combobox" valueField="id" textField="name"
	               url="orders_find_logistics.do"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			支付方式：
	        		</td>
	        		<td colspan="2">
	        			<input name="payType" showNullItem="true" nullItemText="全部" style="width: 130px;" class="mini-combobox" required="true" valueField="keyName" textField="keyValue"
	               			url="dictionary_om_key_val_view.do?typeName=ORDER_PAY_TYPE"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			货款：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="payment" id="orders_payment" enabled="false" style="width: 70px;" value="0"/>
	        			<span style="margin-left: 84px;">运费：</span>
	        			<input class="mini-textbox" emptyText="请输入运费" name="freight" id="orders_freight" onvaluechanged="freightChange();" vtype="float;maxLength:11;negative" style="width: 70px;" value="0"
	        			<sec:authorize url="/orders_freight_read1.do">enabled="true"</sec:authorize> enabled="false"/>
	        			<span style="margin-left: 60px;">应收金额：</span>
	        			<input class="mini-textbox" name="receivable" id="orders_receivable" onfocus="getReceivable();" onvaluechanged="receivableChange();" required="true" style="width: 70px;margin-left: 5px;" value="0"
	        			 vtype="float;maxLength:11;negative" <sec:authorize url="/receivable_read1.do">enabled="true"</sec:authorize> enabled="false"/>
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right" >
	        			实收金额：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="amountPaid" id="amount_paid" vtype="float;maxLength:11;negative" onvaluechanged="amountPaidChange();" style="width: 70px;" required="true"
	        			<sec:authorize url="/amount_paid_read1.do">enabled="true"</sec:authorize> enabled="false"/>
	        			<span style="margin-left: 60px;">使用余额：</span>
	        			<input class="mini-textbox" name="useMoney" id="use_money" style="width: 70px;" value="0" enabled="false"/>
	        			<span style="margin-left: 60px;">剩余金额：</span>
	        			<input class="mini-textbox" name="money" id="customer_money" enabled="false" style="width: 70px;margin-left: 5px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right" >
	        			本单使用积分：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="usePoints" id="orders_use_points" required="true" vtype="int;maxLength:11" style="width: 70px;" enabled="false"/>
	        			<span style="margin-left: 60px;">本单积分：</span>
	        			<input class="mini-textbox" name="points" id="orders_points" enabled="false" style="width: 70px;" />
	        			<span style="margin-left: 60px;">剩余积分：</span>
	        			<input class="mini-textbox" name="integral" id="customer_integral" enabled="false" style="width: 70px;margin-left: 5px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			本单使用红包：
	        		</td>
	        		<td colspan="4">
	        			<input class="mini-textbox" name="useRed" id="orders_use_red" required="true" vtype="int;maxLength:11" style="width: 70px;" enabled="false"/>
	        			<span style="margin-left: 60px;">本单红包：</span>
	        			<input class="mini-textbox" name="red" style="width: 70px;" onfocus="getRed();" required="true" vtype="int;maxLength:11;negative" value="0" id="red" onvaluechanged="redChange();"/>
	        			<span style="margin-left: 60px;">剩余红包：</span>
	        			<input class="mini-textbox" name="redEnvelopes" id="customer_redEnvelopes" enabled="false" style="width: 70px;margin-left: 5px;" />
	        		</td>
	        	</tr>
	        	<tr>
	        		<td align="right">
	        			客户级别变化：
	        		</td>
	        		<td colspan="4">
	        			<span id="keyCustomerLevel"></span>-------
	        			<input id="customer_level" emptyText="请选择..." showNullItem="true" nullItemText="全部" style="width: 138px;" class="mini-combobox" valueField="keyName" textField="keyValue"
	               			url="dictionary_cm_key_val_view.do?typeName=CUSTOMER_LEVEL_TYPE" value="1" onvaluechanged="levelChanged();"/>
	        		</td>
	        	</tr>
	        </table>
	        <div style="text-align:center;padding:10px;">               
	        	<sec:authorize url='/orders_edit_save1.do'>
	            <a class="mini-button" onclick="onOk" style="width:150px;" id="edit_orders">修改订单信息</a>     
	            </sec:authorize>
	        </div>        
	    </form>
	    <div id="win1" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
		<div id="win2" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
		<div id="win3" class="mini-window" allowDrag="false" showHeader="false" title="选择地址—省份" style="width: 300px;height: 150px;">
		</div>
	</fieldset>
	<fieldset style="border:solid 1px #aaa;padding:3px;">
		<legend >订单产品信息</legend>
		<div id="datagrid1" class="mini-datagrid" style="width:800px;height:auto;" showPager="false" allowResize="false" url="orders_product_view.do" idField="id">
	        <div property="columns">
	            <div field="medicineName" width="15%" headerAlign="center" align="center">名称</div>                
	            <div field="price" width="5%" align="center" headerAlign="center">价格</div>
	            <div field="prePrice" width="6%" headerAlign="center" align="center">优惠价格</div>            
	            <div field="quantity" width="5%" align="center" headerAlign="center">数量</div>            
	            <div field="freight" width="5%" headerAlign="center" align="center">运费</div>
	            <div field="usePoints" width="6%" headerAlign="center" align="center">积分抵扣</div>                
	            <div field="useRed" width="6%" headerAlign="center" align="center">红包抵扣</div>                
	            <div field="totalPrice" width="6%" headerAlign="center" align="center">实际价格</div>                
	            <div field="discountPrice" width="6%" headerAlign="center" align="center">折扣价格</div>                
	            <div field="premiums" width="4%" headerAlign="center" align="center">赠品</div>           
	            <div field="ridePin" width="4%" headerAlign="center" align="center">搭销</div>   
	            <sec:authorize url='/orders_product_del1.do'>         
	            <div name="action" width="5%" headerAlign="center" align="center" renderer="onActionRenderer" cellStyle="padding:0;" id="on_action_renderer">操作</div>
	            </sec:authorize>
	        </div>
    	</div>    
        <input class="mini-hidden" name="ordersId" id="orders_id"/>
        <input class="mini-hidden" id="call_orders_status"/>
        <input class="mini-hidden" id="orders_status"/>
        <input class="mini-hidden" id="warehouse_status"/>
        
		<div id="form2">
            <input class="mini-hidden" name="id"/>
            <table cellspacing="10" cellpadding="0">
                <tr>
                    <td style="width:130px;" align="right">药品：</td>
                    <td style="width:230px;">
                    	<input name="medicineId" emptyText="请选择..." style="width: 150px;" allowInput="false" required="true" class="mini-buttonedit" onbuttonclick="onButtonEdit"/>
                    </td>
                    <input class="mini-hidden" id="inventory"/>
                	<td style="width:130px;" align="right">数量：</td>
                	<td>
                		<input name="quantity" style="width: 60px;" required="true" class="mini-textbox" value="1" vtype="int;maxLength:11;negative"/>
                	</td>
                </tr>
                <tr>
                	<td align="right">产品价格：</td>
                	<td>
                		<input name="price" id="price" style="width: 60px;" class="mini-textbox" enabled="false" value="0"/>
                		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;优惠价格：
                		<input name="prePrice" id="pre_price" required="true" style="width: 60px;" vtype="float;maxLength:11;negative"  class="mini-textbox" value="0"
                		<sec:authorize url="/pre_price_read1.do">enabled="true"</sec:authorize> enabled="false"/>
                	</td>
                	<td align="right">运费：</td>
                	<td>
                		<input name="freight" style="width: 60px;" required="true" class="mini-textbox" vtype="float;maxLength:11;negative" value="0"/>
                	</td>
                </tr>
                <tr>
                	<td align="right">积分抵扣：</td>
                	<td>
                		<input name="usePoints" id="use_points" required="true" style="width: 60px;" class="mini-textbox" onvaluechanged="usePointsValid" value="0" vtype="int;maxLength:11;negative"/>
                		<span id="use_points_error" class="errorText"></span>
                	</td>
                	
                	<td align="right">红包抵扣：</td>
                	<td>
                		<input name="useRed" id="use_red" style="width: 60px;" required="true" class="mini-textbox" onvaluechanged="useRedValid" value="0" vtype="int;maxLength:11;negative"/>
                		<span id="use_red_error" class="errorText"></span>
                	</td>
                </tr>
            </table>
        </div>
		<div style="text-align:center;padding:10px;">         
			<sec:authorize url='/orders_product_save1.do'>
		    <a class="mini-button" onclick="onOk2" style="width:150px;" id="save_product">保存产品信息</a>       
		    </sec:authorize>
	    </div>
	</fieldset>
	<div style="text-align:center;padding:10px;">           
		<sec:authorize url='/orders_edit_status1.do'>    
	    <a class="mini-button" onclick="onOk3" style="width:150px;" id="become_effective">订单生效</a>  
	    </sec:authorize>     
	    <a class="mini-button" onclick="againSubmitOk" style="width:150px; margin-left: 20px;display: none;" id="again_submit">再次提交审核</a>     
	    <a class="mini-button" onclick="onCancel" style="width:150px; margin-left: 20px;">订单关闭</a>     
    </div>
</body>
</html>

<script type="text/javascript">
	mini.parse();
	var form1 = new mini.Form("form1");
	
	var customerId = mini.get("customer_id");
	var customerMoney = mini.get("customer_money");
	var customerIntegral = mini.get("customer_integral");
	var customerRedEnvelopes = mini.get("customer_redEnvelopes");
	var callOrdersStatus = mini.get("call_orders_status");
	var ordersStatus = mini.get("orders_status");
	var warehouseStatus = mini.get("warehouse_status");
	
	var contactNos = mini.getbyName("contactNos");
	var contactNo = mini.getbyName("contactNo");
	
	var becomeEffective = mini.get("become_effective");	// 订单生效
	var againSubmit = mini.get("again_submit");			// 再次提交按钮
	var editOrders = mini.get("edit_orders");			// 修改订单信息按钮
	var saveProduct = mini.get("save_product");			// 保存产品信息按钮
	
	// 页面加载时设置数据
	function SetData(data) {
		data = mini.clone(data);
		console.info(data.row);
		form1.setData(data.row);
		form1.setChanged(false);
		grid.load({ordersId: data.row.id });
		ordersId.setValue(data.row.id);
		callOrdersStatus.setValue(data.row.callStatusVal);
		ordersStatus.setValue(data.row.ordersStatusVal);
		warehouseStatus.setValue(data.row.warehouseStatusVal);
		if(data.row.ordersStatusVal == 3 || data.row.ordersStatusVal == 6) {	// 订单未通过、取消单
			againSubmit.show();
			becomeEffective.hide();
		} else if(data.row.ordersStatusVal == 2) {		// 无效单不能重新编辑
			editOrders.hide();
			saveProduct.hide();
			grid.hideColumn("action");
			mini.getbyName("medicineId").disable();
			form1.setEnabled(false);
			form2.setEnabled(false);
		}
		if(data.row.callStatusVal == 38) {				// 正在输入的订单
			againSubmit.hide();
		} else if(data.row.callStatusVal == 39) {		// 订单生效隐藏生效按钮
			becomeEffective.hide();
		}
		if(data.row.warehouseStatusVal == 4) {				// 签收后不能编辑订单11
			mini.get("edit_orders").hide();
			mini.get("save_product").hide();
			grid.hideColumn("action");
			mini.getbyName("medicineId").disable();
			form1.setEnabled(false);
			form2.setEnabled(false);
		}
		
		$.post("customer_find_info.do", {id: data.row.customerId, ordersId: data.row.id}, function(data){
			customerId.setValue(data.customer.id);
			$("#keyCustomerLevel").text(data.customer.keyCustomerLevel);
			
			// 正在输入、审核不通过、取消、无效、退单的订单需要减去订单中对应值
			if(callOrdersStatus.getValue() == "38" || ordersStatus.getValue() == "3" || ordersStatus.getValue() == "6" || 
					ordersStatus.getValue() == "2" || warehouseStatus.getValue() == "2") {
				
				customerMoney.setValue(numSub(data.customer.money, useMoney.getValue()));					// 剩余余额
				customerIntegral.setValue(numSub(data.customer.integral, ordersUsePoints.getValue()));		// 剩余积分
				var cRed = numAdd(data.customer.redEnvelopes, red.getValue());								// 客户红包+赠送红包
				customerRedEnvelopes.setValue(numSub(cRed, ordersUseRed.getValue()));						// 再减去本单使用红包
				
			} else { // 生效、通过、发货、签收直接读取就可以
				customerMoney.setValue(data.customer.money);
				customerIntegral.setValue(data.customer.integral);
				customerRedEnvelopes.setValue(data.customer.redEnvelopes);
			}
			
			$("#orders_count").text(data.customer.ordersCount);
			$("#back_count").text(data.customer.backCount);
		}, "json");
	}
	
/*-----------------------------加载省市区数据-------------------------*/
	// 弹出省份列表
 	var win1 = mini.get("win1");
 	var province = mini.get("province");
 	var provinceVal = mini.get("province_val");
 	function focusP(e) {
 		var el=e.sender.getEl();
		var bodyEl1 = win1.getBodyEl();
		$(bodyEl1).empty();
		$.post("customer_manage_find_province.do", {}, function(data) {
			win1.showAtEl(el, {
			   xAlign:"left",
			   yAlign:"below"
			});
			$.each(data, function(i, obj) {
				$(bodyEl1).append("</li><a href='javascript:loadC("+obj.id+", "+'"'+obj.pName+'"'+")' style='padding: 5px;'>"+obj.pName+"</a>");
			});
		}, "json");
		
 	}
 
 	// 通过省加载城市
 	var city = mini.get("city");
 	var cityVal = mini.get("city_val");
 	var win2 = mini.get("win2");
 	function loadC(p_id, p_name) {
 		var el = city.getEl();
		var bodyEl2 = win2.getBodyEl();
		$(bodyEl2).empty();
		$.post("customer_manage_find_city.do", {provinceId: p_id}, function(data) {
	 		provinceVal.setValue(p_id);
	 		province.setValue(p_name);
	 		win1.hide();
			win2.showAtEl(el, {
			   xAlign:"left",
			   yAlign:"below"
			});
			$.each(data, function(i, obj) {
				$(bodyEl2).append("<a href='javascript:loadD("+'"'+obj.id+'"'+", "+'"'+obj.cName+'"'+", "+'"'+obj.zipCode+'"'+")' style='padding: 5px;'>"+obj.cName+"</a>");
				mini.parse();
			});
		}, "json");
 	}
 	
 	// 通过城市加载区县
 	var win3 = mini.get("win3");
 	var district = mini.get("district");
 	var districtVal = mini.get("district_val");
 	var zipCode = mini.getbyName("zipCode");
 	function loadD(c_id, c_name, c_zipCode) {
 		var el = district.getEl();
 		var bodyEl3 = win3.getBodyEl();
 		zipCode.setValue(c_zipCode);
 		$(bodyEl3).empty();
 		$.post("customer_manage_find_district.do", {cityId: c_id}, function(data) {
 			city.setValue(c_name);
 			cityVal.setValue(c_id);
 			win2.hide();
 			win3.showAtEl(el, {
 			   xAlign:"left",
 			   yAlign:"below"
 			});
 			$.each(data, function(i, obj) {
				$(bodyEl3).append("<a href='javascript:setD("+obj.id+", "+'"'+obj.dName+'"'+")' style='padding: 5px;'>"+obj.dName+"</a>");
				mini.parse();
			});
 		}, "json");
 	}
 	
 	// 设置区县
 	function setD(d_id, d_name) {
 		win3.hide();
 		districtVal.setValue(d_id);
 		district.setValue(d_name);
 	}
 	
/*-----产品信息--------------------------------------------------------------------------------------------------------------------------*/ 	
 	
 	//客户级别变化
 	var customerLevel = mini.get("customer_level");
 	function levelChanged() {
 		$.post("customer_edit_level.do", {customerLevel: customerLevel.getValue(), id: customerId.getValue()});
 	}

 // 运费变化,设置实收金额
 	function freightChange() {
 		ordersFreight.validate();
 		if(ordersFreight.isValid() == false) return;
 		
 		if(grid.getData().length > 0) {
	 		amountPaid.setValue(numAdd(ordersReceivable.getValue(), ordersFreight.getValue()));
	 		amountPaidChange();
		} else {
			mini.alert("请先添加产品！");
			ordersFreight.setValue(0);
		}
 	}
 	
 // 应收金额获取焦点时获得当前应收金额值
 	var oriReceivable = 0;
 	function getReceivable() {
 		ordersReceivable.validate();
 		if(ordersReceivable.isValid() == false) return;
 		oriReceivable = ordersReceivable.getValue();
 	}

 	// 应收金额改变时触发
 	function receivableChange() {
 		ordersReceivable.validate();
 		if(ordersReceivable.isValid() == false) return;
 		if(ordersId.getValue().length > 0) {
 			if(grid.getData().length > 0) {
 				ordersPoints.setValue(ordersReceivable.getValue().toString().split(".")[0]);			// 本单积分（应收金额取整）
		 		amountPaid.setValue(numAdd(ordersReceivable.getValue(), ordersFreight.getValue()));
		 		amountPaidChange();
		 		calcDiscount();
 			} else {
 				mini.alert("请先添加产品！");
 				ordersReceivable.setValue(0);
 			}
 		}
 	}
 	
 	// 实收金额修改时设置积分
 	var amountPaid = mini.get("amount_paid");			// 实收金额
 	var ordersPoints = mini.get("orders_points");		// 本单积分
 	var useMoney = mini.get("use_money");				// 使用余额
 	function amountPaidChange() {
 		amountPaid.validate();
 		if(amountPaid.isValid() == false || amountPaidEvent() == false) return;
 		if(grid.getData().length > 0) {
 			var or = numAdd(ordersReceivable.getValue(), ordersFreight.getValue());	// 应收金额 + 运费
 			var op = amountPaid.getValue();											// 实收金额
 			
 			if(Number(or) > Number(op)) {								// 应收金额  > 实收金额时
 				if(Number(useMoney.getValue()) != 0) {
 					customerMoney.setValue(numAdd(customerMoney.getValue(), useMoney.getValue()));	// 客户余额先加回原来使用余额
 				}
	 			var um = numSub(or, op);										// 使用余额 = （应收金额+运费） - 实收金额
 				useMoney.setValue(um);
 				customerMoney.setValue(numSub(customerMoney.getValue(), um));	// 客户余额再减去当前使用余额
 				saveAmountPaidChange();
 			} else {	// 应收金额  < 实收金额
 				customerMoney.setValue(numAdd(customerMoney.getValue(), useMoney.getValue()));	// 客户余额 + 使用余额
 				useMoney.setValue(0);
 				saveAmountPaidChange();
 			}
 		} else {
 			mini.alert("请先添加产品！");
 			amountPaid.setValue(0);
 		}
 	}

 	// 判断实收金额和客户余额之和是否大于应收金额
 	function amountPaidEvent() {
		var or = numAdd(ordersReceivable.getValue(), ordersFreight.getValue());		// 应收金额 + 运费
		var ap = numAdd(amountPaid.getValue(), customerMoney.getValue());			// 实收金额 + 余额 
		var uap = numAdd(ap, useMoney.getValue());									// 再加上使用余额
		
 		if(Number(or) > Number(uap)) {	
 			mini.alert("实收金额与客户余额之和不能小于应收金额与运费之和！");
 			return false;
 		} else {				// 应收金额 + 运费  < 实收 + 余额 + 使用余额
 			return true;
 		}
 	}
	
 	// 保存实收金额改变
 	function saveAmountPaidChange() {
 		var o = form1.getData(true);
 		var url;
 		if(callOrdersStatus.getValue() == 38) {
 			// 正在输入状态，修改订单请求
 			url = "orders_edit_save.do?id=" + ordersId.getValue();
 		} else {
 			url = "orders_storage_edit.do?id=" + ordersId.getValue();
 		}
 		$.ajax({
	        url: url,
			type: 'post',
			dataType: 'json',
	        data: o,
	        cache: false,
	    });
 	}

 	// 计算产品折扣价
 	function calcDiscount() {
 		if(oriReceivable != 0) {
 			orVal = ordersReceivable.getValue();
 			$.post("orders_edit_calc_discount.do", {id: ordersId.getValue(), receivable: orVal, oriReceivable: oriReceivable}, function(data) {
 				if(data.success) {
 					grid.reload();
 				}
 			}, "json");
 		} else {
 			mini.alert("产品实际价格不能为0，请修改！");
 		}
 	}
 	
 	// 红包获得焦点时触发
 	var originalRed = 0;
 	function getRed() {
 		red.validate();
		if(red.isValid() == false) return;
		originalRed = red.getValue();
 	}
 	
 	// 本单红包更改时添加到剩余红包中
 	var red = mini.get("red");
 	function redChange() {
 		red.validate();
		if(red.isValid() == false) return;
	 	// 先减去原来的红包，再加上当前红包。
 		customerRedEnvelopes.setValue(numSub(customerRedEnvelopes.getValue(), originalRed));
 		customerRedEnvelopes.setValue(numAdd(customerRedEnvelopes.getValue(), red.getValue()));
 		saveAmountPaidChange();
 	}
 	
 // 负数验证
	mini.VTypes["negativeErrorText"] = "不能为负数";
    mini.VTypes["negative"] = function (v) {
    	if(Number(v) < 0) {
    		return false;
    	} else {
    		return true;
    	}
    }
 	
 	// 保存订单基本信息
 	function editSave(o1) {
 		if(form1.isChanged()) {
 			var url;
 	 		if(callOrdersStatus.getValue() == 38) {
 	 			// 正在输入状态，修改订单请求
 	 			url = "orders_edit_save.do?id=" + ordersId.getValue();
 	 		} else {
 	 			url = "orders_storage_edit.do?id=" + ordersId.getValue();
 	 		}
 	 		$.ajax({
 	 	        url: url,
 	 			type: 'post',
 	 			dataType: 'json',
 	 	        data: o1,
 	 	        cache: false,
 	 	        success: function (text) {
 	 	            if(text.success){
 	 	            	mini.alert("修改成功");
 	 	            }else{
 	 	            	mini.alert("数据错误！");
 	 	            }
 	 	          form1.setChanged(false);
 	 	        },
 	 	        error: function (jqXHR, textStatus, errorThrown) {
 	 	            alert(jqXHR.responseText);
 	 	            window.CloseOwnerWindow();
 	 	        }
 	 	    });
 		} else {
 			mini.alert("订单信息未改变");
 		}
 	}
 	
	// 保存基本信息按钮
    function onOk(e) {
    	var o1 = form1.getData(true);
	    form1.validate();
	    if (form1.isValid() == false || amountPaidEvent() == false) return;
	    if(ordersStatus.getValue() == 39) {
	    	mini.confirm("订单已生效，正在等待审核，确定修改？ ", "修改确认",function (action) {
	    		if(action == "ok") {
	    			editSave(o1);
	    		}
	    	});
	    } else {
	    	editSave(o1);
	    }
    }
 	
/*--------订单产品----------------------------------------------------------------*/
	
 	var form2 = new mini.Form("form2");
 	var grid = mini.get("datagrid1");
 	var ordersId = mini.get("orders_id");
 	grid.load({ordersId: ordersId.getValue() });
 	
 	var price = mini.get("price");
 	var prePrice = mini.get("pre_price");
 	var inventory = mini.get("inventory");
 	// 弹出选择产品
 	function onButtonEdit(e) {
        var btnEdit = this;
        mini.open({
            url: "orders_product_select.do",
            title: "选择产品/赠品",
            width: 500,
            height: 350,
            allowResize: false,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = { ordersId: ordersId.getValue() };
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
                //if (action == "close") return false;
                if (action == "ok") {
                    var iframe = this.getIFrameEl();
                    var data = iframe.contentWindow.GetData();
                    data = mini.clone(data);
                    if (data) {
                    	inventory.setValue(data.inventory);
                    	prePrice.setValue(data.price);
                    	price.setValue(data.price);
                        btnEdit.setValue(data.id);
                        btnEdit.setText(data.name);
                    }
                }
            }
        });            
    }
 	
/*-------------------计算函数---------------------------------------------------------------*/
 	// 加法
 	function numAdd(num1, num2) {
	    var baseNum, baseNum1, baseNum2;
	    try {
	        baseNum1 = num1.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum1 = 0;
	    }
	    try {
	        baseNum2 = num2.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum2 = 0;
	    }
	    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
	    return (num1 * baseNum + num2 * baseNum) / baseNum;
	};
	
	// 减法
	function numSub(num1, num2) {
	    var baseNum, baseNum1, baseNum2;
	    var precision;// 精度
	    try {
	        baseNum1 = num1.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum1 = 0;
	    }
	    try {
	        baseNum2 = num2.toString().split(".")[1].length;
	    } catch (e) {
	        baseNum2 = 0;
	    }
	    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
	    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
	    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
	};
	
	// 乘法
	function numMulti(num1, num2) {
	    var baseNum = 0;
	    try {
	        baseNum += num1.toString().split(".")[1].length;
	    } catch (e) {
	    }
	    try {
	        baseNum += num2.toString().split(".")[1].length;
	    } catch (e) {
	    }
	    return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
	};
	
	// 积分、红包抵扣验证
	var usePoints = mini.get("use_points");
	function usePointsValid() {
		usePoints.validate();
 		if(usePoints.isValid() == false) return;
		var el = document.getElementById("use_points_error");
		if(Number(usePoints.getValue()) > Number(customerIntegral.getValue())) {
			el.innerHTML = "不能超过用户现有积分";
			return false;
		} else {
			el.innerHTML = "";
			return true;
		}
	}
	
	var useRed = mini.get("use_red");
	function useRedValid() {
		useRed.validate();
 		if(useRed.isValid() == false) return;
		var el = document.getElementById("use_red_error");
		if(Number(useRed.getValue()) > Number(customerRedEnvelopes.getValue())) {
			el.innerHTML = "不能超过用户现有红包";
			return false;
		} else {
			el.innerHTML = "";
			return true;
		}
	}
 	
   	var ordersReceivable = mini.get("orders_receivable"); 	// 应收金额
   	var ordersPayment = mini.get("orders_payment");			// 货款
   	var ordersFreight = mini.get("orders_freight");			// 运费
   	var ordersUsePoints = mini.get("orders_use_points");	// 本单使用积分
   	var ordersUseRed = mini.get("orders_use_red");			// 本单使用红包
   	
   	// 比较添加的产品，积分和红包总和与价格的大小
   	var quantity = mini.getbyName("quantity");
   	function compare() {
   		var productPrice = numMulti(prePrice.getValue(), quantity.getValue());
   		var redAndPoints = numAdd(usePoints.getValue(), useRed.getValue());
   		if(productPrice >= redAndPoints) {
   			return true;
   		} else {
   			mini.alert("使用红包和积分总和不能大于总价格！");
   			return false;
   		}
   	}
   	
   	// 保存订单产品
   	function editSaveProduct(o) {
   		form2.loading();
   		$.ajax({
	        url: "orders_product_save.do?ordersId=" + ordersId.getValue(),
			type: 'post',
			dataType: 'json',
	        data: o,
	        cache: false,
	        success: function (text) {
	            if(text.success){
	            	grid.load({ordersId: ordersId.getValue() });
	            	var price = numMulti(o.price, o.quantity);				// 单个产品货款 = 价格*数量
	            	var prePrice = numMulti(o.prePrice, o.quantity);		// 单个产品优惠金额 = 优惠价格*数量
	            	var redAndPoint = numAdd(o.usePoints, o.useRed);
	            	var singleAmountPaid = numSub(prePrice, redAndPoint);	// 单个产品实际价格 = 优惠价格-积分/红包抵扣
	            	var prePrice1 = numSub(prePrice, redAndPoint);			// 单个产品应收 = 优惠  - 积分 -红包
	            	var pf = numAdd(singleAmountPaid, o.freight);			// 单品实收金额 = 实际价格+运费
	            	ordersPayment.setValue(numAdd(ordersPayment.getValue(), price));				// 订单货款
	            	ordersFreight.setValue(numAdd(ordersFreight.getValue(), o.freight));			// 订单运费
	            	ordersReceivable.setValue(numAdd(ordersReceivable.getValue(), prePrice1));		// 订单应收金额
	            	amountPaid.setValue(numAdd(amountPaid.getValue(), pf));							// 订单实收金额
	            	ordersUsePoints.setValue(numAdd(ordersUsePoints.getValue(), o.usePoints));		// 订单使用积分
	            	
	            	var thisOrdersPoints = ordersReceivable.getValue().toString().split(".")[0];
	            	ordersPoints.setValue(thisOrdersPoints);											// 本单积分（应收金额取整）
	            	
	            	ordersUseRed.setValue(numAdd(ordersUseRed.getValue(), o.useRed));				// 订单使用红包
	            	
	            	customerIntegral.setValue(numSub(customerIntegral.getValue(), usePoints.getValue()));			// 剩余积分设值
	            	customerRedEnvelopes.setValue(numSub(customerRedEnvelopes.getValue(), useRed.getValue()));		// 剩余红包设值
	            	
	            	var o1 = form1.getData(true);
	            	var url;
	            	if(callOrdersStatus.getValue() == 38) {
	         			// 正在输入状态，修改订单请求
	         			url = "orders_edit_save.do?id=" + ordersId.getValue();
	         		} else {
	         			url = "orders_storage_edit.do?id=" + ordersId.getValue();
	         		}
	            	$.ajax({
	    		        url: url,
	    				type: 'post',
	    				dataType: 'json',
	    		        data: o1,
	    		        cache: false,
	    		        success: function (text) {
	    		            if(text.success){
	    		            	form2.reset();
	    		            	form2.unmask();
	    		            }
	    		        },
	    		    });
	            }else{
	            	mini.alert("数据错误(订单id不能为空)！");
	            }
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	            alert(jqXHR.responseText);
	            window.CloseOwnerWindow();
	        }
	    });
   	}
   	
   	// 保存订单产品按钮
 	function onOk2() {
 		var o = form2.getData(true); 
	    form2.validate();
	    if (form2.isValid() == false || usePointsValid() == false || useRedValid() == false || compare() == false) return;
	    if(ordersStatus.getValue() == 39) {
	    	
	    	if(quantity.getValue() > inventory.getValue()) {
	    		mini.confirm("该产品库存量不足，确定继续购买？", "产品库存不足提示",
		            function (action) {
		                if (action == "ok") {
		                	
		                	mini.confirm("订单已生效，正在等待审核，确定修改？ ", "修改确认",function (action) {
		        	    		if(action == "ok") {
		        	    			editSaveProduct(o);
		        	    		}
		        	    	});
		                }
		            }
				);
	    	} else {
	    		mini.confirm("订单已生效，正在等待审核，确定修改？ ", "修改确认",function (action) {
    	    		if(action == "ok") {
    	    			editSaveProduct(o);
    	    		}
    	    	});
	    	}
	    } else {
	    	editSaveProduct(o);
	    }
 	}
 	
 	// 删除订单产品
 	function onActionRenderer() {
 		return '<a style="width:150px;" href="javascript:del()" >删除</a>';
 	}
 	
 	// 删除订单产品
 	function delProduct(row) {
 		$.ajax({
            url: "orders_product_del.do?id=" + row.id,
            dataType: 'json',
            success: function (text) {
           		if(text.success){
           			ordersPayment.setValue(numSub(ordersPayment.getValue(), numMulti(row.price, row.quantity)));	// 删除减去货款
           			ordersFreight.setValue(numSub(ordersFreight.getValue(), row.freight));				// 删除减去运费
           			ordersReceivable.setValue(numSub(ordersReceivable.getValue(), row.discountPrice));	// 删除减去应收金额
           			
           			if(grid.getData().length-1 == 0){														// 产品为0是，设置应收为0
           				ordersReceivable.setValue(0);
           				ordersFreight.setValue(0);
           			}
           			
           			var apUm = numAdd(amountPaid.getValue(), useMoney.getValue());						// 实收金额+使用余额
           			if(ordersReceivable.getValue() == 0) {												// 应收金额为0了，实收也必须为0
           				amountPaid.setValue(0);
           			} else {
               			amountPaid.setValue(numSub(apUm, row.discountPrice));								// 删除时产品计算实收金额
           			}
           			
           			customerMoney.setValue(numAdd(customerMoney.getValue(), useMoney.getValue()));		// 设置剩余余额
           			useMoney.setValue(0);																// 设置使用余额
           			
           			ordersPoints.setValue(ordersReceivable.getValue().toString().split(".")[0]);		// 删除产品本单积分（应收金额取整）
           			ordersUsePoints.setValue(numSub(ordersUsePoints.getValue(), row.usePoints));		// 本单使用积分-产品用积分
           			ordersUseRed.setValue(numSub(ordersUseRed.getValue(), row.useRed));					// 本单使用红包-产品用红包
           			customerIntegral.setValue(numAdd(customerIntegral.getValue(), row.usePoints));		// 剩余积分
           			customerRedEnvelopes.setValue(numAdd(customerRedEnvelopes.getValue(), row.useRed));	// 剩余红包
                    grid.reload();
                    var o1 = form1.getData(true);
	            	var url;
	            	if(callOrdersStatus.getValue() == 38) {
	         			// 正在输入状态，修改订单请求
	         			url = "orders_edit_save.do?id=" + ordersId.getValue();
	         		} else {
	         			url = "orders_storage_edit.do?id=" + ordersId.getValue();
	         		}
                    $.ajax({
	    		        url: url,
	    				type: 'post',
	    				dataType: 'json',
	    		        data: o1,
	    		        cache: false,
	    		        success: function (text) {
	    		            if(text.success){
	    		            	
	    		            }
	    		        },
	    		    });
	            }else{
	            	mini.alert("数据错误(id不能为空)！");
	            }
            }
        });
 	}
 	
 	// 删除订单产品按钮
 	function del() {
 		var row = grid.getSelected();
 	    if (row) {
 	    	if(ordersStatus.getValue() == 39) {
 	    		mini.confirm("订单已生效，正在等待审核，确定修改？ ", "修改确认",function (action) {
 		    		if(action == "ok") {
 		    			delProduct(row);
 		    		}
 		    	});
 		    } else {
 		    	delProduct(row);
 		    }
 	    } else {
 	        mini.alert("请选中一条记录");
 	    }
 	}
    
    function onCancel(e) {
    	window.CloseOwnerWindow("cancel");
    }
    
    // 验证剩余金额、积分、红包是否是负数
    function validNegative () {
    	if(Number(customerMoney.getValue()) < Number(0) || Number(customerIntegral.getValue()) < Number(0) || Number(customerRedEnvelopes.getValue()) < Number(0)) {
    		mini.alert("剩余金额、剩余积分、剩余红包不能为负数，请修改后生效。");
    		return false;
    	}
    }
    
    // 订单生效
    function onOk3() {
    	var url = "";
    	if(ordersStatus.getValue() == 6) {
    		// 无效单再次生效请求
    		url = "orders_again_submit.do";
    	} else {
    		url = "orders_edit_status.do";
    	}
    	if(grid.getData().length == 0) {
    		mini.alert("订单未选择任何产品，不能生效！");
    	} else {
    		if(amountPaidEvent() == false) return;
    		if(validNegative() == false) return;
	    	$.post(url, {id: ordersId.getValue()}, function(data) {
	    		if(data.success) {
	    			window.CloseOwnerWindow("succ");
	    		}
	    	}, "json");
    	}
    }
    
    // 订单再次提交
    function againSubmitOk() {
    	var o1 = form1.getData(true);
    	if(amountPaidEvent() == false) return;
    	$.ajax({
	        url: "orders_again_submit.do?id=" + ordersId.getValue(),
			type: 'post',
			dataType: 'json',
	        data: o1,
	        cache: false,
	        success: function (text) {
	            if(text.success){
	            	window.CloseOwnerWindow("succ");
	            }
	        },
	    });
    }
    
/*连接WebSocket*/
    jQuery.openWebSocket("ws://172.16.2.11:8080/websocket");
    
// 连接成功时执行
    function webSocketOnOpen(event) {
		
 	}
    
    // 呼出电话
   	var winOutgoing = mini.get("win—outgoing");
    var outNumId = mini.get("outNumId");
    var addNum = mini.get("addNum");
    
    function outgoing1() {
		winOutgoing.showAtPos("right", "top");
		outNumId.setValue(contactNo.getValue());
    }
    
    function outgoing2() {
		winOutgoing.showAtPos("right", "top");
		outNumId.setValue(contactNos.getValue());
    }
    
    function outgoingOk() {
    	$.post("alternately_cur_extension.do", function(data) {
    		if(null != data.phoneNum && 0 != data.phoneNum && data.phoneNum.length > 0) {
    			var arr = new Array();
    			arr[0] = addNum.getValue();
    			arr[1] = outNumId.getValue();
    			var callNum = arr.join("");
    			jQuery.dail(data.phoneNum, callNum);
    			winOutgoing.hide();
    			outNumId.setValue("");
    			addNum.setValue("");
    		} else {
    			mini.alert("未登录分机");
    		}
    	}, "json")
    }
    
    function onClose2() {
    	winOutgoing.hide();
    	outNumId.setValue("");
    	addNum.setValue("");
    }
    
   	// 验证号码格式
   	mini.VTypes["numTypeErrorText"] = "号码格式不正确";
    mini.VTypes["numType"] = function (v) {
    	if(v.length > 0) {
    		var reMobile = new RegExp("^0?1[34578]\\d{9}$");
        	var rePhone = new RegExp("^(010|02\\d|0[3-9]\\d{2})?\\d{7,8}$");
        	if(reMobile.test(v)) {
        		return true;
        	} else if(rePhone.test(v)) {
        		return true;
        	} else {
        		return false;
        	}
    	} else {
    		return true;
    	}
    }

    // 查看客户原来订单
    function historyOrders() {
    	mini.open({
            url: "customer_history_orders_init.do",
            allowResize:false,
            title: "已下订单", width: 850, height: 300,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = { customerId: customerId.getValue(), id: ordersId.getValue()};
                iframe.contentWindow.SetData(data);
            }
        });
    }
    
</script>